package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.conmon.response.JsonResult;
import cn.tedu._05weibo.conmon.response.StatusCode;
import cn.tedu._05weibo.mapper.UserMapper;
import cn.tedu._05weibo.pojo.dto.UserRegDTO;
import cn.tedu._05weibo.pojo.entity.User;
import cn.tedu._05weibo.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
@Api(tags = "01.用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    //用户注册
    @ApiOperation(value = "注册功能")
    @PostMapping("reg")
    public JsonResult reg(@RequestBody UserRegDTO userRegDTO){
       String username=userRegDTO.getUsername();
       UserVO userVO = userMapper.selectByUsername(username);
       if(userVO!=null){
           return new JsonResult(StatusCode.USERNAME_EXISTS);
       }
       User user = new User();
       BeanUtils.copyProperties(userRegDTO,user);
       user.setCreated(new Date());
       userMapper.insertUser(user);
       return JsonResult.ok();
    }
    //用户登录
    @ApiOperation(value = "登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody @Validated UserRegDTO userRegDTO, @ApiIgnore HttpSession httpSession) {//使用HttpSession实现会话保持
       String username = userRegDTO.getUsername();
       UserVO userVO = userMapper.selectByUsername(username);
       if (userVO == null) {
           return new JsonResult(StatusCode.USERNAME_ERROR);//用户名错误
       }
       if (userRegDTO.getPassword().equals(userVO.getPassword())) {
           httpSession.setAttribute("user", userVO);//将用户信息保存到session中
           return JsonResult.ok();
       }
       return new JsonResult(StatusCode.PASSWORD_ERROR);
   }
    //获取当前用户功能
    @ApiOperation(value = "获取当前用户功能")
    @GetMapping("currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession httpSession){
        UserVO userVO=(UserVO)httpSession.getAttribute("user");
        return JsonResult.ok(userVO);
    }
    //用户退出
    @ApiOperation(value = "用户退出功能")
    @GetMapping("logout")
    public void logout(@ApiIgnore HttpSession httpSession){
       httpSession.removeAttribute("user");
    }

}
